
var pageBean = null;
var dataList = {};
var clients = {};

$(document).ready(function(e) {

    $(".select1").uedSelect({
        width : 345
    });
    $(".select2").uedSelect({
        width : 70
    });
    $(".select3").uedSelect({
        width : 100
    });
    initialClientLevle();
    
    $("#btnSave").click(save);
    $("#btnCancle").click(cancle);
    $("#member_add").click(add);

    $("#deleteusers").click(deleteUsers);

    $("#headerCheckBox").change(function(){
        $("INPUT[rowchecked]").prop({checked:$(this).is(':checked')});
    });
    //当文件变化的时候上传
    $("#uploadpic").change(uploadSpaceImage);

    search(1);
    $('#uploadModal').on('hide.bs.modal', function () {
    	$("#excel_icon_upload").attr("data-path","");
			$("#padd_client_id").val(0).trigger("change");
			$("#padd_space_id").val(0).trigger("change");
    	})
    	  $('#uploadModal').on('hidden.bs.modal', function () {
    	$("#excel_icon_upload").attr("data-path","");
			$("#padd_client_id").val(0).trigger("change");
			$("#padd_space_id").val(0).trigger("change");
    	})
    	
    	
    	

    initialSpace();//加载和初始化空间信息选择
   // initialClient();
    initialSelect();//初始化页面上的选择框数据
    
    $("#excel_icon_upload").click(function(){
    	$("#upload_file").click();
    })
    //上传excel模版文件
    $("#upload_file").change(function(){
    	if(!$("#upload_file").val()){
    		alert("请选择要上传的文件！");
    		return;
    	}
    	var accessToken = localStorage.getItem('accessToken');
    	$('#upload').ajaxSubmit({
    		dataType : "json",
    		headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
    		beforeSubmit : function(request) { 
    			//alert("正在上传"); 
    		}, 
    		success : function(result, textStatus, response) { 
    			//alert(JSON.stringify(result));
    			if(result.status==0){    				
    				$("#excel_icon_upload").attr("data-path",result.data);
    				$("#upload_file_info").html("上传成功！");
    			}else{
    				$("#upload_file_info").tml(result.message);
    			}
    			 
    			//alert('成功上传！'); 		 
    		},
    		error : function(result) {
    			//alert('上传失败！'); 
    		} 
    	});
    })
    
    $("#btn_upload_save").click(function(){

    	$path = $("#excel_icon_upload").attr("data-path");
    	if(!$path){
    		alert("请选择要上传的文件！");
    		return;
    	}
    	$client_id = $("#padd_client_id").val();
    	if(!$client_id){
    		alert("请选择所属客户！");
    		return;
    	}
    	$space_id = $("#padd_space_id").val();
    	if(!$space_id){
    		alert("请选择入驻空间！");
    		return;
    	}
    	$.ajax({
            url: '/euc/member/batchImport',
            data:{"file_path":$path,"client_id":$client_id,"space_id":$space_id},
            beforeSend: function(request) {
            	var accessToken = localStorage.getItem('accessToken');
                request.setRequestHeader("accessToken",accessToken );
            },
            async: true,
            contentType:'application/json;charset=utf-8',
            type: 'GET',
            success: function (result, textStatus, response) {
       			if(result.status==1){
       				$('#uploadModal').modal('hide');
       				$("#excel_icon_upload").attr("data-path","");
       				$("#padd_client_id").val(0).trigger("change");
       				$("#padd_space_id").val(0).trigger("change");
       				
       			}else{
       				alert(result.message);
       			}
            },
            error: function () {
            	/*alert("error");*/
            }  
        });
    	
    	
    })
    $("#btn-cardsave").click(function(){
    	id= $("#btn-cardsave").attr('data-id');
    	$cardnum = $("#bindCardNum").val();
    	if(!$cardnum){
    		alert("请输入会员卡");return false;
    	}
    	var cardNumber = $.trim($("#bindCardNum").val());
    	try{
    		cardNumber = parseInt(cardNumber);
    		//if(cardNumber >= 1 && cardNumber <= 50){
    		//	alert("会员无法绑定系统占用ID！");
    		//	return ;
    		//}
    	}catch(e){
    		alert("请输入有效会员卡号！");
    		return;
    	}
    	bindHanWangCard($cardnum,id);    	
    })
    
    $(".add_space_id,.add_client_id").change(function(){
    	$clientid=parseInt($(".add_client_id").val());
    	$spaceid=parseInt($(".add_space_id").val());
      	
    	if($clientid>0&&$spaceid>0){
    		getBelongSpace($clientid,$spaceid)
    	}else{
    		$("#room_div").html('');
    		$("#add_room_list").hide();
    	}
    })

    
    
});


function bindHanWangCard(cardNumber,memberId){
	$.ajax({
        url: '/euc/member/bindWristBand',
        data:{"wristBandsNumber":cardNumber,"memberId":memberId },
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'GET',
        success: function (result, textStatus, response) {
        	if(result.status===0){
        		$("#bindCardNum").val('');
        		$("#bindCardModal").modal('hide');
//        		alert("绑卡成功");
        		alert(result.message);
//        		window.location.reload();
        		search(pageBean.currentPage);
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function getRequestJson(requestJson){
    if(requestJson == null){
        requestJson = {};
    }

    var idCard = $("input[name='idCard']").val();
    if(idCard == ''){
        alert("请输入身份证");
        return ;
    }
    requestJson["idCard"] = idCard;

    var userName = $("input[name='name']").val();
    if(userName == ''){
        alert("请输入姓名");
        return false;
    }
    requestJson["name"] = userName;

    var spaceId = $("select[name='spaceId']").val();
    if(spaceId == '0'){
        alert("请选择入驻空间");
        return false;
    }
    requestJson["spaceId"] = spaceId;

    var clientId = $("select[name='clientId']").val();
    if(clientId == '0'){
        alert("请选择所属客户");
        return false;
    }
    requestJson["clientId"] = clientId;


    var employStatus = $("select[name='employStatus']").val();
    requestJson["employStatus"] = employStatus;

    var faceUrl = $("input[name='faceUrl']").val();
    requestJson["faceUrl"] = faceUrl;

    var email = $.trim($("input[name='email']").val());
    if(email == ''){
        alert("请输入邮箱");
        return false;
    }
    requestJson["email"] = email;

    var mobile = $("input[name='mobile']").val();
    if(mobile == ''){
        alert("请输入电话号码");
        return false;
    }
    requestJson["mobile"] = mobile;
    var isAdmin = $("input[name='isAdmin']:checked").val();

    requestJson["isAdmin"] = isAdmin;
    requestJson["roomAccess"] =getRoonVal();



    return requestJson;
}

function save(){

    var requestJson = {};
    requestJson = getRequestJson(requestJson);
    if(requestJson == false){
        return false;
    }

    $.ajax({
        url: '/euc/member/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
            //alert(JSON.stringify(datas));
            if(datas.status == 0){
                $("DIV[name='member_list']").show();
                $("DIV[name='memberAdd']").hide();
                search(pageBean.currentPage);
            }
            alert(datas.message);
        },
        error: function () {
            /*alert("error");*/
        }
    });
}

function update(user){
    if(user == null){
        return false;
    }
    user = getRequestJson(user);
    if(user == false){
        return false;
    }

    $.ajax({
        url: '/euc/member/add',
        data:JSON.stringify(user),
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
            if(datas.status == 0){
                $("DIV[name='member_list']").show();
                $("DIV[name='memberAdd']").hide();
                alert("编辑成功");
                //window.location.reload();
              	search(pageBean.currentPage);
            }else{            	
            	alert(datas.message);
            }
        },
        error: function () {
            /*alert("error");*/
        }
    });
}

function cancle(){
    $("DIV[name='member_list']").show();
    $("DIV[name='memberAdd']").hide();
	$("#face_url").val('');
	$("#headImage").attr('src','');
	clearForm();
}

function clearForm(){
    $("input[name='user_name']").val('');
    $("input[name='userName']").val('');
    $("input[name='name']").val('');
    $("select[name='userGender']").val('男').trigger('change');
    $("input[name='age']").val('');
    $("input[name='email']").val('');
    $("input[name='idCard']").val('');
    $("input[name='mobile']").val('');
    $("input[name='userPassword']").val('');
    $("input[name='rePassword']").val('');

    $("input[name='idCard']").val('');

    $("#space_id").val('0').trigger('change');
    $("#client_id").val('0').trigger('change');

}

function setForm(user){
    $("input[name='user_name']").val(user.userName);
    $("input[name='name']").val(user.name);
    $("select[name='userGender']").val(user.gender).trigger('change');
    $("input[name='age']").val(user.age);
    $("input[name='email']").val(user.email);
    $("input[name='idCard']").val(user.idCard);
    $("input[name='mobile']").val(user.mobile);
    $("input[name='userPassword']").val(user.password);
    $("input[name='rePassword']").val(user.password);
    $("input[name='idCard']").val(user.idCard);
}

function add(){
    $("#operator").html("添加");
    clearForm();
    $("input[name='user_name']").removeAttr("disabled");
    $("#btnSave").unbind();
    $("#btnSave").click(save);
    $("#isAdmin").removeAttr("checked");
    $("input:radio[name='isAdmin']").eq(0).attr("checked",'checked');
    $("DIV[name='member_list']").hide();
    $("DIV[name='memberAdd']").show();
    $("#room_div").html('');
	$("#space_id").val($("#space_id option").eq(1).attr('value')).trigger('change');
	$kehu = $("input[name='parameter']").val();
	if($kehu){
		var $kid=$("#client_id").find("option:contains("+$kehu+")").index();
		if($kid>0){
			$("#client_id").val($("#client_id option").eq($kid).attr('value')).trigger('change');
		}else{
			$("#client_id").val($("#client_id option").eq(1).attr('value')).trigger('change');
		}
	}else{
		$("#client_id").val($("#client_id option").eq(1).attr('value')).trigger('change');		
	}

    initialSpace();//加载和初始化空间信息选择
    initialClient();
	$("#add_room_list").attr("data-ids",0);
}


function detail(id){
	initialSpace();
    $("#face_url").val('');
	$("#headImage").attr('src','');
	
    var currentData = dataList[id];
    clearForm();
    setForm(currentData);
    $("#add_room_list").attr('data-ids',currentData.roomAccess);

    $("#operator").html("编辑");
    if(currentData.faceUrl){
    	$("#face_url").val(currentData.faceUrl);
    	$("#headImage").attr('src',currentData.faceUrl);
    	$("#show_head").show();
    }
    
    $("input[name='user_name']").attr("disabled",true);
    $("DIV[name='member_list']").hide();
    $("#room_div").html('');
    $("#client_id").val(currentData.clientId).trigger('change');
    $("#space_id").val(currentData.spaceId).trigger('change');
 

    //getBelongSpace(currentData.clientId,currentData.clientId)
    $("#isAdmin").removeAttr("checked");
    $("input:radio[name='isAdmin']").eq(currentData.isAdmin).attr("checked",'checked');

    $("DIV[name='memberAdd']").show();
    $("#btnSave").unbind();
    $("#btnSave").click(function(){
        update(currentData);
    });
}

function deleteUsers(){
    if(confirm("确定删除选中的会员?")){
        var result = true;
        $("INPUT[rowchecked]:checked").each(function(index,element){
            var id = $(element).prop("name");
            var requestJson = {id:id};
            $.ajax({
                //url: '/euc/user/deleteUser',
                data:JSON.stringify(requestJson),
                beforeSend: function(request) {
                    var accessToken = localStorage.getItem('accessToken');
                    request.setRequestHeader("accessToken",accessToken );
                },
                dataType: 'JSON',
                async: false,
                contentType:'application/json;charset=utf-8',
                type: 'POST',
                success: function (result, textStatus, response) {
                	search(pageBean.currentPage);
                },
                error: function () {
                    result = false;
                }
            });
        });
        if(result == true){
            var cur = $('.paginItem.current').find("a").html();
            cur = parseInt(cur);
            search(cur);
        }
    }
}


function deleteUser(id){
    if(confirm("确定删除该用户?")){
        var requestJson = {memberId:id,status:4};
        $.ajax({
             url: '/euc/member/deleteOrBroken',
            data:JSON.stringify(requestJson),
            beforeSend: function(request) {
                var accessToken = localStorage.getItem('accessToken');
                request.setRequestHeader("accessToken",accessToken );
            },
            dataType: 'JSON',
            async: true,
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            success: function (result, textStatus, response) {
                var cur = $('.paginItem.current').find("a").html();
                cur = parseInt(cur);
                search(cur);
                if(result.message ==='success'){
                	result.message ='删除成功';
                }
                alert(result.message);
            },
            error: function () {
            	console.log("error");
            }
        });
    }
}

function initailPageNumber(totalPage,currentPage,pageLength){
    try{
        var midNumber = Math.ceil((pageLength-2)/2);
        var paginList = $(".paginList");
        $(paginList).empty();
        var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
        var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
        if( totalPage <= pageLength - 2){
            $(prev).appendTo($(".paginList"));
            for(var i = 1; i<totalPage+1; i++){
                var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
                if(i == currentPage){
                    pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
                }
                $(pagenItem).appendTo($(".paginList"));
            }
            $(next).appendTo($(".paginList"));
        }else{
            if(currentPage <= midNumber){
                $(prev).appendTo($(".paginList"));
                for(var i=1;i <= pageLength - 4;i++){
                    var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
                    if(i == currentPage){
                        pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
                    }
                    $(pagenItem).appendTo($(".paginList"));
                }
                var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
                $(pagenItem).appendTo($(".paginList"));
                var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
                $(pagenItem).appendTo($(".paginList"));
                $(next).appendTo($(".paginList"));
            }if(totalPage - currentPage < midNumber){

                var index = totalPage;
                for(var i=1;i <= pageLength - 4;i++){
                    var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
                    if(index == currentPage){
                        pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
                    }
                    $(pagenItem).prependTo($(".paginList"));
                    index--;
                }
                var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
                $(pagenItem).prependTo($(".paginList"));
                var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
                $(pagenItem).prependTo($(".paginList"));
                $(prev).prependTo($(".paginList"));

                $(next).appendTo($(".paginList"));
            }else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

                pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
                $(pagenItem).prependTo($(".paginList"));
                var count = midNumber - 3;
                for(var i = 1; i<=count;i++){
                    pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
                    $(pagenItem).prependTo($(".paginList"));
                    pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
                    $(pagenItem).appendTo($(".paginList"));
                }
                pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
                $(pagenItem).prependTo($(".paginList"));
                pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
                $(pagenItem).prependTo($(".paginList"));
                $(prev).prependTo($(".paginList"));

                pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
                $(pagenItem).appendTo($(".paginList"));
                pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
                $(pagenItem).appendTo($(".paginList"));
                $(next).appendTo($(".paginList"));
            }
        }
        $(".paginItem").click(function(){
            if($(this).hasClass("more")){
                //alert("more");
                return;
            }else if($(this).find(".pagepre").length > 0){
                var cur = $('.paginItem.current').find("a").html();
                cur = parseInt(cur);
                if(cur > 1){
                    search(cur - 1);
                }
            }else if($(this).find(".pagenxt").length > 0 ){
                var cur = $('.paginItem.current').find("a").html();
                cur = parseInt(cur);
                if(cur < totalPage){
                    search(cur + 1);
                }
            }else{
                var cur = $(this).find("a").html();
                cur = parseInt(cur);
                search(cur);
            }
        });
    }catch(e){/*alert(e.messge);*/}
}

function search(currentPage){
	var clientName = $.trim(localStorage.getItem('clientName'));
	if(clientName != ''){
		$("INPUT[name='parameter']").val(clientName);
		localStorage.removeItem('clientName');
	}
    var parameter = $("INPUT[name='parameter']").val();
    var requestJson = {currentPage:currentPage,data:{"parameter":parameter}};

    $.ajax({
        url: '/euc/member/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
            //alert(JSON.stringify(result));
            pageBean = result.data;
            $("#userTable").empty();//清空列表
            $.each(result.data.list,function(i,data){
                var html = '<tr>';
                html += '<td style="width:30px;"><input rowchecked name="'+data.id+'" type="checkbox" value="" /></td>';
                html += '<td style="width:70px;">' + (i+1) +'</td>';
                html += '<td style="width:160px;">' + data.mobile + '</td>';
                html += '<td>' + (data.name!=null?data.name:"-") + '</td>';
                html += '<td>' + (data.nickName!=null?data.nickName:"-") + '</td>';
                html += '<td>' + (data.employStatusDesc!=null?data.employStatusDesc:"-") + '</td>';
                html += '<td>' + (data.belongSpaceName!=null?data.belongSpaceName:"-") + '</td>';
                html += '<td>' + (data.companyName !=null?data.companyName:"-")+ '</td>';
                html += '<td>' + data.createTime + '</td>';
                html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteUser('+data.id+');" class="tablelink">删除</a>&nbsp;&nbsp;&nbsp;';
                if(data.employStatus!=3){
                    html += '<a href="javascript:leavel('+data.id+');" id="le'+data.id+'" class="tablelink">离场</a>&nbsp;&nbsp;&nbsp;';             	
                }
                html += '<a href="javascript:bindCard('+data.id+');" id="c'+data.id+'" data-card="'+data.wristBandsNumber+'" data-time="'+data.bindTime+'"  class="tablelink">绑卡</a></td>';
                html += '</tr>';
                $("#userTable").append(html);
                dataList[data.id] = data;
            });
            $("#totalRow").html(pageBean.totalRow+'&nbsp;');
            $("#currentPage").html(pageBean.currentPage+'&nbsp;');
            $("#pageSize").html(pageBean.pageSize+'&nbsp;');

            var pageLength = 15;
            initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);
        },
        error: function () {
        	console.log("error");
        }
    });
}
function leavel(memberId){
    if(confirm("确定将此用户设为‘离场’状态吗?")){
        var requestJson = {memberId:memberId,status:3};
        $.ajax({
            url: '/euc/member/deleteOrBroken',
            data:JSON.stringify(requestJson),
            beforeSend: function(request) {
                var accessToken = localStorage.getItem('accessToken');
                request.setRequestHeader("accessToken",accessToken );
            },
            dataType: 'JSON',
            async: true,
            contentType:'application/json;charset=utf-8',
            type: 'POST',
            success: function (result, textStatus, response) {
            	$("#le"+memberId).remove();
                var cur = $('.paginItem.current').find("a").html();
                cur = parseInt(cur);
                search(cur);
                alert(result.message);
            },
            error: function () {
                console.log("error");
            }
        });
    }
}
function uploadSpaceImage(){
    $("#show_head").hide();
    var accessToken = localStorage.getItem('accessToken');
    $('#headForm').ajaxSubmit({
        dataType : "json",
        async: false, 
        headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
        beforeSubmit : function(request) {
            //alert("正在上传");
        },
        success : function(result, textStatus, response) {
            //alert(JSON.stringify(result));
           // console.log(result);
           // console.log(response);
        	if(result.status==0){
                $("#headImage").prop("src",result.data);
                $("#show_head").show();
                $("input[name='headImage']").val(result.data);
                $("#face_url").val(result.data);
                $("[formParameter='pic'][name='url']").val(result.data);
                $("#uploadpic").val("");
                alert(result.message);
        	}else{
        		alert(result.message);
        	}

            //alert('成功上传！');
        },
        error : function(result) {
            //alert('上传失败！');
            $("#show_head").hide();

        }
    });
}



function initialSpace(){//初始化空间信息
    try{
        var spaceString = localStorage.getItem('space');
        spaces = $.parseJSON(spaceString);
        return true;
    }catch(e){
        console.log(e.messge);
    }
    $.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
            try{
                $.each(result,function(index,data){
                    spaces[data.id] = data;
                });
                var spaceJson = JSON.stringify(spaces);
                localStorage.setItem('space',spaceJson);
            }catch(e){
                /*alert(e.message);*/
            }
        },
        error: function () {
            /*alert("error");*/
        }
    });
}

function initialClient(){
	return ;
    try{
        var clientString = localStorage.getItem('client');
        clients = $.parseJSON(clientString);
    }catch(e){
        console.log(e.messge);
    }
    $.ajax({
        url: '/euc/client/list',
        data:'',
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'GET',
        success: function (result, textStatus, response) {
            var clientSelect = $("#client_id");
            try{
                $.each(result,function(index,data){
                        $('<option value="'+ data.id
                            +'">'+ (data.companyName != ''?data.companyName:data.memberName) +'</option>').appendTo($(clientSelect));
                });
               // console.log(clients);
                var clientJson = JSON.stringify(clients);
                localStorage.setItem('client',clientJson);
            }catch(e){
                console.log(e.message);
            }
        },
        error: function () {
            /*alert("error");*/
        }
    });
}


function initialSelect(){//初始化页面上的选择框数据

    var spaceSelect = $("#space_id");
    var padd_spaceSelect = $("#padd_space_id");
    $.each(spaces,function(key,space){
        $('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
        $('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(padd_spaceSelect));
    });
    $(spaceSelect).val(0).trigger('change');


   // $(clientSelect).val(0).trigger('change');

}

function getBelongSpace(clientId,spaceId,accessList){
	
	//console.log($("#add_room_list").attr("data-ids"));
	
	$("#add_room_list").show();
    if(clientId =='' || spaceId =='')
        return ;
    var requestJson = {"clientId":clientId,"spaceId":spaceId};
    var rooms='';
    var $ids = $("#add_room_list").attr("data-ids");
    var $_isarray=0;
    if($ids&&$ids.indexOf(",")>0){
    	
    	$rooms = $ids.split(",");
    	$_isarray=1;
    }else{
    	$rooms =parseInt($ids);
    }
    
    $.ajax({
        url: '/euc/room/member_room',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	$("#room_div").html('');
            $.each(result,function(i,data){
    			if($rooms|| $rooms==0){
    				if($rooms instanceof Array){
    					var testStr=','+$rooms.join(",")+",";     					
    					if(testStr.indexOf(","+data.id+",")!=-1){
    						$("#room_div").append('<input name="roomlist" type="checkbox" checked value="'+data.id+'" />'+data.roomName+'&nbsp&nbsp');
    						return true;
    					}
    				}else{

    					if($rooms===data.id||$rooms==0){
    						$("#room_div").append('<input name="roomlist" type="checkbox" checked value="'+data.id+'" />'+data.roomName+'&nbsp&nbsp');
    						return true;
    					}
    				}

    			}
    			if($("#operator").html() == '添加'){
    				$("#room_div").append('<input name="roomlist" type="checkbox" checked value="'+data.id+'" />'+data.roomName+'&nbsp&nbsp');
    			}else{
    				$("#room_div").append('<input name="roomlist" type="checkbox" value="'+data.id+'" />'+data.roomName+'&nbsp&nbsp');
    			}
            })
        },
        error: function () {
            console.log(e.message);
        }
    });

}
function getRoonVal(){
	var data = $("input[name='roomlist']:checked");  
	$list=new Array();
	data.each(function(i,attrib){
		$list.push($(this).val());
	});
	return $list.toString();
}

function initialClientLevle(){
	$.ajax({
        url: '/euc/client/memberclient',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	var clientLevle = $("#client_id");        	
        	var padd_clientLevle = $("#padd_client_id");        	
        	$.each(result,function(index,data){	
        		if(data.clientType=="企业"){
        			$('<option value="'+ data.id +'">'+ data.companyName +'</option>').appendTo($(clientLevle));
        			$('<option value="'+ data.id +'">'+ data.companyName +'</option>').appendTo($(padd_clientLevle));
        		}else{
        			$('<option value="'+ data.id +'">'+ data.memberName +'</option>').appendTo($(clientLevle));
        			$('<option value="'+ data.id +'">'+ data.memberName +'</option>').appendTo($(padd_clientLevle));
        		}
           		//clientLevles[data.id] = data;
   			});
        	console.log();
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}
//绑定会员
function bindCard(id){
	$name="#c"+id;
	$("#btn-cardsave").attr("data-id",id);
	$("#bindCardNum").val('');//chushihua
	cardnum = $($name).attr('data-card');
	cardtime = $($name).attr('data-time');
	$("#bcardLists tbody").html('');
	//console.log(cardnum);
	if(cardnum&& (cardnum!== 'null')){
		$("#bcardLists tbody").append("<tr id=\"a"+id+"\" class=\"carlist\"><td>"+cardnum+"</td><td>"+cardtime+"</td><td><a onclick=\"unbing("+id+")\">解绑</a>&nbsp;&nbsp;<a onclick=\"bindHanWangCard("+cardnum+","+id+")\">重新同步</a></td></tr>")
	}
	$("#bindCardModal").modal({'show':true,'backdrop':'static'});
	
}
function unbing(id){
	$.ajax({
        url: '/euc/member/cancelBind',
        data:{"memberId":id },
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'GET',
        success: function (result, textStatus, response) {
        	if(result.status==0){
        		$("#bindCardNum").val('');
        		$("#bindCardModal").modal('hide');
        		$("#a"+id).remove();
//        		alert("解绑成功");
        		alert(result.message);
//        		window.location.reload();
        		search(pageBean.currentPage);
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}
